using UnityEngine;

public class ParallaxBackground : MonoBehaviour
{
    /// <summary>
    /// 用于存储主摄像机的引
    /// </summary>
    private GameObject cam;
    /// <summary>
    /// 用于控制视差效果的强度。值越接近 0，背景移动越慢；值越接近 1，背景移动越快。
    /// </summary>
    [SerializeField] private float parallaxEffect;
    /// <summary>
    /// 用于记录背景的初始 X 坐标
    /// </summary>
    private float xPos;
    /// <summary>
    /// 背景精灵的宽度，用于实现背景的循环。
    /// </summary>
    private float length;

    private void Awake()
    {
        cam = Camera.main.gameObject;
        //camOriginalPosX = cam.transform.position.x;
        length = GetComponent<SpriteRenderer>().bounds.size.x;
        xPos = transform.position.x;
    }

    private void LateUpdate()
    {
        // 摄像机移动的距离，乘以 (1 - parallaxEffect)，表示背景相对于摄像机的移动差异。
        float camPosX = cam.transform.position.x;
        float disMove = camPosX * (1 - parallaxEffect);
        // disToMove：背景实际需要移动的距离，乘以 parallaxEffect。
        float disToMove = cam.transform.position.x * parallaxEffect;
        transform.position = new Vector3(xPos + disToMove, transform.position.y);

        if (disMove > xPos + length)
        {
            xPos += length;
        }
        else if (disMove < xPos - length)
        {
            xPos -= length;
        }
    }
}
